package sk.ygor.xtemplate;

import java.util.Map;
import java.lang.reflect.Method;
import java.io.Serializable;

/**
 * User: ygor
 * Date: 14.11.2005
 * Time: 4:16:38
 */
public class ContentToken implements Serializable {

    public int type;
    public String value;
    public String subValue;

    public static int TEXT = 0;
    public static int VARIABLE = 1;

    public ContentToken(int type, String value, String subValue) {
        this.type = type;
        this.value = value;
        this.subValue = subValue;
    }

    public String toString() {
        if (subValue == null) {
            return "{" + value + "}";
        } else {
            return "{" + value + "." + subValue + "}";
        }

    }

    public String getText(Map<String, Object> space) throws XTemplateException {
        if (type == TEXT) {
            return value;
        } else {
            try {
                Object result = space.get(value);
                if (subValue != null) {
                    if (result instanceof Map) {
                        return ((Map) result).get(subValue).toString();
                    } else {
                        return beanValue(result, subValue).toString();
                    }
                } else {
                    return result.toString();
                }
            } catch (Exception e) {
                throw new XTemplateException("Could not resolve template variable: " + toString(), e);
            }
        }
    }

    private Object beanValue(Object bean, String fieldName) throws Exception {
        String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
        Method method = bean.getClass().getMethod(methodName);
        return method.invoke(bean);
    }


}
